﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseFunction;
using YFTOpenAPI;
using WebRequestHelp = YFTOpenAPI.WebRequestHelp;

namespace YY.Web.MyAgent.financial_information
{
    public partial class Recharge : BaseFunction.LoginHelp
    {
        public static string UserName = "";
        public static string UserId = "";
        public static string Billno = "";
        public static string CheckMoney = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                YY.Model.agent_users userinfor = base.GetSessionModel();
                UserName = userinfor.user_name;
                UserId = userinfor.amount;//财务账号
                span_PayType.Value = "";
            }
            CheckMoney = txt_Money.Value.ToString() + " 元";
            lblCZTime.Text = DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒");
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (span_PayType.Value == "环讯支付")
            {
                string key = ConfigurationManager.AppSettings["MerchantNumber"].ToString();
                string Ip = BaseFunction.StaticTableClass.SystemConfigHelp.GetSystemConfigValue("YFT_IP");
                string Money = txt_Money.Value;
                if (!Money.Contains("."))
                {
                    Money = Money + ".00";
                }
                else
                {
                    if (Money.Split('.')[1].Length < 2)
                    {
                        Money = Money + "0";
                    }
                }
                string Amount = Convert.ToString(Math.Round(decimal.Parse(Money), 2));//金额 保留俩位小数
                string DispAmount = Amount;//显示金额
                string BillDate = DateTime.Now.ToString("yyyyMMdd");//订单日期
                Random rand = new Random();
                Billno = DateTime.Now.ToString("yyyyMMddhhmmss") + rand.Next(10000, 99999); //产生订单号
                #region 创建订单
                string typeid = "6";
                string typename = "充值";
                string Fund = Amount;
                string TradeTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                string TradeContent = typename;
                string Remark = "于" + TradeTime + "；进行了" + typename + "交易；交易失败，未完成充值。";
                string Status = "0";//未支付
                string OtherName = "环讯支付";
                string eguid = OpenAPI.EncryptPar(UserId);
                string eType = OpenAPI.EncryptPar(typeid);
                string eFund = OpenAPI.EncryptPar(Fund);
                string eStatus = OpenAPI.EncryptPar(Status);
                string eTradeTime = OpenAPI.EncryptPar(TradeTime);
                string eTradeContent = OpenAPI.EncryptPar(TradeContent);
                string eRemark = OpenAPI.EncryptPar(Remark);
                string eOtherName = OpenAPI.EncryptPar(OtherName);
                string eOrderNumber = OpenAPI.EncryptPar(Billno);
                string md5 = OpenAPI.MD5Encrypt(eguid + eType + eFund + eStatus + eTradeTime + eTradeContent + eRemark + eOtherName + eOrderNumber, key);
                string paraminfor = "md5=" + md5 + "&key=" + key + "&eUserId=" + eguid + "&eType=" + eType + "&eFund=" + eFund + "&eStatus=" + eStatus + "&eTradeTime=" + eTradeTime + "&eTradeContent=" + eTradeContent + "&eRemark=" + eRemark + "&eOtherName=" + eOtherName + "&eOrderNumber=" + eOrderNumber;
                string urlloa = Ip + "/HTTP/AddYiyangTradeInfor.aspx";
                string result = WebRequestHelp.PostDataToUrl(paraminfor, urlloa);
                if (result == "1000")
                {
                    Response.Redirect("ErrorInfor.aspx?infor=校验码失败");
                }
                else
                {
                    if (result == "1")
                    {
                        #region 调用充值接口
                        string Attach = TradeTime + "|" + typename + "|" + key + "|" + UserId;//商户数据包格式 交易时间|交易类型名称|key
                        string eAmount = OpenAPI.EncryptPar(Amount);
                        string eDispAmount = OpenAPI.EncryptPar(DispAmount);
                        string eBillDate = OpenAPI.EncryptPar(BillDate);
                        string eBillno = OpenAPI.EncryptPar(Billno);
                        string eAttach = OpenAPI.EncryptPar(Attach);
                        string Md5 = OpenAPI.MD5Encrypt(eAmount + eDispAmount + eBillDate + eBillno, key);
                        string param = "eAmount=" + eAmount + "&key=" + key + "&eDispAmount=" + eDispAmount + "&eBillDate=" + eBillDate + "&eBillno=" + eBillno + "&eAttach=" + eAttach + "&md5=" + Md5;
                        string url = Ip + "/HTTP/Pay.aspx";
                        
                        Response.Write("<script language='javascript'>window.open('" + url + "?" + param + "','_blank');</script>");
                        MessageBox.ResponseScript(this.Page, "showdiv();");
                        
                        return;
                        //MessageBox.JsprintMsg(this.Page, "即将跳转支付界面", url);
                        //MessageBox.ResponseScript(this.Page,"window.open('" + url + "?" + param + "');");
                        #endregion
                    }
                }
                #endregion
            }
        }

        /// <summary>
        /// 点击支付成功按钮
        /// </summary>
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            string errorinfor = "";
            if (CheckRechargeMoneyOrder(UserId, Billno, out errorinfor))
            {
                //支付已经完成 并且成功 跳转到支付成功的提示画面
                string emoney = OpenAPI.EncryptFund(CheckMoney, "yiyang");
                Response.Redirect("RechargeMoneySuccess.aspx?money=" + emoney);
            }
            else
            {
                //支付失败 跳转到支付失败的提示画面
                Response.Redirect("ErrorInfor.aspx?infor=" + errorinfor);
            }
        }

        /// <summary>
        /// 点击支付失败按钮
        /// </summary>
        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            string errorinfor = "";
            if (CheckRechargeMoneyOrder(UserId, Billno, out errorinfor))
            {

                Response.Redirect("ErrorInfor.aspx?infor=''");
            }
            else
            {
                //支付失败 跳转到支付失败的提示画面
                Response.Redirect("ErrorInfor.aspx?infor=" + errorinfor);
            }
        }

        /// <summary>
        /// 订单确认
        /// </summary>
        private bool CheckRechargeMoneyOrder(string userid, string Billno, out string errorinfor)
        {
            string key = ConfigurationManager.AppSettings["MerchantNumber"].ToString();
            string Ip = BaseFunction.StaticTableClass.SystemConfigHelp.GetSystemConfigValue("YFT_IP");
            string eguid = OpenAPI.EncryptPar(UserId);
            string eBillno = OpenAPI.EncryptPar(Billno);
            string action = "CheckRechargeMoneyOrder";
            string eaction = OpenAPI.EncryptPar(action);
            string md5 = OpenAPI.MD5Encrypt(eaction + eguid + eBillno, key);
            string paraminfor = "md5=" + md5 + "&key=" + key + "&eguid=" + eguid + "&eBillno=" + eBillno + "&eaction=" + eaction;
            string urlloa = Ip + "/HTTP/YFTPay.aspx";
            string result = WebRequestHelp.PostDataToUrl(paraminfor, urlloa);
            if (result == "1000" || result == "fail")
            {
                //签名验证错误 或者验证失败（该订单不是该用户的）
                if (result == "1000")
                {
                    errorinfor = "签名验证错误";
                }
                else
                {
                    errorinfor = "提交错误,该订单与您当前登录不符合";
                }
                return false;
            }
            else
            {
                if (result == "-1" || result == "0")
                {
                    //处于交易中 或者交易失败
                    if (result == "-1")
                    {
                        errorinfor = "您的订单正处于处于交易中..";
                    }
                    else
                    {
                        errorinfor = "对不起，亲！您还未支付，请重新充值。";
                    }
                    return false;
                }
                else
                {
                    //交易成功
                    errorinfor = "交易成功";
                    return true;
                }
            }
        }
    }
}